import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Button, Row, Form, Input } from 'antd';
import cass from 'classnames';
import { config } from '../../configs';
import { runListeners } from '../../utils/util';
import s from './index.less';
import Forget from './forget';

const FormItem = Form.Item;

class Login extends Component {
	state = {
		forget: false
	}

	handleOk = () => {
		const {
			dispatch,
			form: {
				validateFieldsAndScroll,
			},
		} = this.props;
		validateFieldsAndScroll((errors, values) => {
			if (errors) {
				return;
			}
			dispatch({ type: 'login/login', payload: values });
		});
	}

	render() {
		const { forget } = this.state;
		const { login, form: { getFieldDecorator } } = this.props;
		const { loginLoading } = login;

		return (
			<div className={cass(s.form, { [s.forgetForm]: forget })}>
				<div className={s.logo}>
					{/* <img alt={'logo'} src={config.logo} /> */}
					<span>{config.name}</span>
				</div>
				<form className={s.login}>
					<FormItem hasFeedback>
						{getFieldDecorator('username', {
							rules: [
								{
									required: true,
									message: '请输入用户名'
								},
							],
						})(<Input onPressEnter={this.handleOk} placeholder="用户名" />)}
					</FormItem>
					<FormItem hasFeedback>
						{getFieldDecorator('password', {
							rules: [
								{
									required: true,
									message: '请输入密码'
								},
							],
						})(<Input type="password" onPressEnter={this.handleOk} placeholder="密码" />)}
					</FormItem>
					<Row>
						<Button type="primary" onClick={this.handleOk} loading={loginLoading}>
							登 录
						</Button>
					</Row>
					<span className={cass('cursor', s.forgetSpan)} onClick={() => this.setState({ forget: true })}>忘记密码</span>
				</form>
				<Forget back={() => this.setState({ forget: false })} />
			</div>
		);
	}
}

Login.propTypes = {
	form: PropTypes.object,
	login: PropTypes.object,
	dispatch: PropTypes.func,
};

export default connect(state => {
	runListeners(state);
	return { login: state.login };
})(Form.create()(Login));
